package edu.msse.signup.service;


import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

import org.springframework.orm.jpa.support.JpaDaoSupport;

import edu.msse.signup.domain.Event;
import edu.msse.signup.domain.Users;


public class UsersService  extends JpaDaoSupport{
	EntityManagerFactory emf =
        Persistence.createEntityManagerFactory("pu");
	@SuppressWarnings("unchecked")
	public boolean authenticateUser(String emailAddress, String password){
		List<Users> userList=emf.createEntityManager().createQuery("from Users u where u.emailAddress=? and u.password=?" ).setParameter(1, emailAddress).setParameter(2, password).getResultList();
		
		if(userList.size()>0)
			return true;
		else
			return false;
	}
	@SuppressWarnings("unchecked")
	public boolean activateUser(String emailAddress, int key){
		EntityManager emg=emf.createEntityManager();
		List<Users> userList=emg.createQuery("from Users u where u.emailAddress=? and u.randomNumber=?" ).setParameter(1, emailAddress).setParameter(2, key).getResultList();
		if(userList.size()<0)
			return false;
		else
		{
			for(Users u: userList)
			{
				EntityTransaction tx=emg.getTransaction();
				tx.begin();
				u.setIsActive(true);
				u=emg.merge(u);
				emg.persist(u);
				tx.commit();
				
			}
			
			return true;
		}
	}

	@SuppressWarnings("unchecked")
	public List<Users> getAllUsers()
	{
		
		List<Users> userList=emf.createEntityManager().createQuery("from Users u").getResultList();
		return userList;
	}
	
	@SuppressWarnings("unchecked")
	public List<Users> findUsersByEmailAddress(String EmailAddress)
	{
		
		List<Users> userList=emf.createEntityManager().createQuery("from Users u where u.emailAddress =?").setParameter(1,EmailAddress).getResultList();
		return userList;
	}
	
	@SuppressWarnings("unchecked")
	public Users updateUser(Users u)
	{
		EntityManagerFactory emf =
	        Persistence.createEntityManagerFactory("pu");
		EntityManager jpa = emf.createEntityManager();
		
        EntityTransaction tx = jpa.getTransaction();
        try {
            tx.begin();
            u=jpa.merge(u);
            jpa.persist(u);
            tx.commit();
            
        } catch (Exception x) {
        	x.printStackTrace();
        	tx.rollback();
        	return null;
            
        }
		return u;
	}	
	
	 @SuppressWarnings("unchecked")
		public List<Users> getVolunteers(Event event) {
			return getJpaTemplate().find(
		                "select u from Users u, Event e, TimeSlot t, Position p where e = ? and ((p.event = " +
		                "e and u in elements(p.users)) " +
		                "or (t.position in elements(e.positions) and u in elements(t.users)))", event);
		}
}
